/**
 * 
 */
package com.service;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth.model.Account;
import com.util.Loggable;
import com.utils.dbcp.ConnectionManager;
import com.utils.dbcp.ModelGenerator;

public class AbstractService {
	
	protected String dbcp = "";
	
	private static Map<String, Integer> idmap = new HashMap<String, Integer>();
	
	private static Object idlock = new Object();
	
	protected int getTableId(String table)
	{
		synchronized (idlock) {
			if (!idmap.containsKey(table))
			{
				String sql = "select ifnull(max(id),1000) from " + table;
				ModelGenerator<Integer> mg = new ModelGenerator<Integer>(Integer.class);
				idmap.put(table, mg.generate(dbcp, sql));
			}
			int id = idmap.get(table);
			id += 1;
			idmap.put(table, id);
			return id;
		}
	}

	protected void logTableOperate(String table, String type, Account operator, Loggable lo)
	{
		String sql = 
				"insert into operatelog(id,operatetime,tablename,operate,operator,loggable) " +
			    "values(" + getTableId("operatelog") + ",now(),'" + table + "','" + type + "','" + 
						operator.getId() + "','" + encodeDb((lo != null ? lo.toLogString() : "")) + "')";
		ConnectionManager.getInstance().execute(dbcp, sql);
	}
	
	protected String formatContractDate(Date d)
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(d);
	}
	
	protected String toInsertString(Object obj, String table)
	{
		String tableFields = "";
		String tableValues = "";
		for (Field field : obj.getClass().getDeclaredFields()) {
			try {
				field.setAccessible(true);
				if (tableFields.length() > 0)
				{
					tableFields += ",";
					tableValues += ",";
				}
				tableFields += field.getName();
				System.out.println(field.getName() + " : " + field.getGenericType());
				if (field.getGenericType().toString().equals("int") 
						|| field.getGenericType().toString().equals("short")
						|| field.getGenericType().toString().equals("byte")
						|| field.getGenericType().toString().equals("long")
						|| field.getGenericType().toString().equals("float")
						|| field.getGenericType().toString().equals("double")
						|| field.getGenericType().toString().equals("class java.lang.Integer")
						|| field.getGenericType().toString().equals("class java.lang.Short")
						|| field.getGenericType().toString().equals("class java.lang.Byte")
						|| field.getGenericType().toString().equals("class java.lang.Long")
						|| field.getGenericType().toString().equals("class java.lang.Float")
						|| field.getGenericType().toString().equals("class java.lang.Double"))
				{
					tableValues += field.get(obj).toString();
				}
				else if (field.getGenericType().toString().equals("class java.util.Date"))
				{
					tableValues += "'" + formatDate((Date) field.get(obj), "yyyy-MM-dd HH:mm:ss") + "'";
				}
				else
				{
					tableValues += "'" + field.get(obj).toString() + "'";
				}
			} catch (IllegalArgumentException e1) {
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			}
		}
		if (tableFields.length() > 0)
			return "insert into " + table + "(" + tableFields +") values(" + tableValues + ")";
		return "";
	}

	protected String formatDate(Date date, String fmt)
	{
		Date d = new Date();
		String f = "yyyy-MM-dd HH:mm:ss";
		
		if (date != null)
			d = date;
		if (fmt != null && fmt.length() > 0)
			f = fmt;
		//System.out.println(f);
		SimpleDateFormat sdf = new SimpleDateFormat(f);
		return sdf.format(d);
	}

	protected boolean checkQueryDimension(String dimension, String key) {
		if (dimension == null)
			return false;
		String d[] = dimension.split(";");
		for (int n = 0; n < d.length; n++)
			if (d[n].equals(key))
				return true;
		return false;
	}
	
	protected String encodeDb(String value)
	{
		if (value == null || value.length() == 0)
			return "";
		return value.replace("'", "\\'");
	}
	
}
